<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog v-model="visible" title="订单详情" @close="handleClose" v-loading="loading">
        <div class="contaoner">
            <div class="left">
                <div class="title">发货人信息</div>
                <div>发货人：{{ express_info.send_name }}</div>
                <div style="margin: 10px 0">地址：{{ express_info.send_full_address }}</div>
                <div>联系电话：{{ express_info.send_mobile }}</div>
            </div>
            <div class="right">
                <div class="title">物流信息</div>
                <div>快递类型：{{ express_info.company?.company_name }}</div>
                <div style="margin: 10px 0">快递单号：{{ express_info.express_number }}</div>
                <div>发货时间：{{ orderinfo.create_time }}</div>
            </div>
        </div>
        <div class="infinite-list" style="overflow: auto">
            <el-table border :data="orderinfo?.order_goods">
                <el-table-column label="商品信息" prop="name">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <el-image
                                style="width: 100px; height: 130px"
                                :src="scope.row?.goods_image"
                                :fit="scope.row?.goods_name"
                                :preview-src-list="[scope.row?.goods_image]"
                                hide-on-click-modal
                                preview-teleported
                            />
                            <div style="flex: 1; margin-left: 12px">
                                <div>{{ scope.row?.goods_name }}</div>
                                <div>{{ scope.row?.card?.ean }}</div>
                                <div>{{ scope.row?.card?.tags }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="商品单价" prop="price"> </el-table-column>
                <el-table-column label="商品规格" prop="sku_name"> </el-table-column>
                <el-table-column label="数量" prop="num"> </el-table-column>
                <el-table-column label="商品总价">
                    <template #empty> 123 </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <div v-if="!orderinfo.unboxing_video">
                <span style="font-size: 22px; font-weight: 600">开箱视频:</span>&nbsp;&nbsp;&nbsp;
                <el-button class="table-header-operate" type="primary" @click="startRecording">开始录制</el-button>
                <el-button class="table-header-operate" type="danger" @click="stopRecording">停止录制</el-button>
                <el-button class="table-header-operate" type="success" @click="downloadVideo">开始上传</el-button>
                <span v-if="size">视频大小：{{ size.toFixed(2) }}M</span> &nbsp;&nbsp;&nbsp;
                <span style="font-size: 12px; color: #999">摄像头自动拍摄开箱视频，点击上传</span>
                <video ref="video" id="video" autoplay></video>
            </div>
            <video v-if="videoSrc || videoshow" :src="videoSrc ? videoSrc : ''" autoplay controls width="200" height="150"></video>
            <div style="margin-top: 20px" v-if="orderinfo.status != 6">
                <span style="font-size: 22px; font-weight: 600">是否确认收货:</span>&nbsp;&nbsp;&nbsp;
                <el-radio-group v-model="radioValue" @change="changeRadio" class="ml-4">
                    <el-radio v-if="orderinfo.status == 1" :label="1" size="large">直接收获</el-radio>
                    <el-radio v-if="orderinfo.status == 1" :label="2" size="large">拒绝收货</el-radio>
                    <el-radio v-if="orderinfo.status == 1 || orderinfo.status == 2" :label="3" size="large">暂不收货，协商价格</el-radio>
                </el-radio-group>
            </div>
            <div v-if="radioValue === 1"><span>支付金额确认：</span><el-input value="1000000" style="width: 240px" :disabled="true" /></div>
            <div v-if="radioValue === 2" style="display: flex">
                <span>拒绝原因：</span
                ><el-input v-model="remark" style="width: 400px; height: 150px" :rows="2" type="textarea" placeholder="请输入拒绝原因" />
            </div>
            <div v-if="radioValue === 3">
                <div>
                    <span>协商金额：</span
                    ><el-input :disabled="orderinfo.status == 2" v-model="consult_money" placeholder="请输入协商金额" style="width: 240px"></el-input>
                </div>
                <div style="display: flex; margin-top: 10px">
                    <span>原因：</span>
                    <el-input
                        :disabled="orderinfo.status == 2"
                        v-model="remark"
                        style="width: 400px; height: 150px"
                        :rows="2"
                        type="textarea"
                        placeholder="请输入拒绝原因"
                    />
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer" v-if="orderinfo.status != 6">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSave" v-if="orderinfo.status != 2"> 确认 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { inject, reactive, ref, watch } from 'vue'
import { ElMessage, selectGroupKey } from 'element-plus'
import { useI18n } from 'vue-i18n'
// import FormItem from '/@/components/formItem/index.vue'
// import Webcam from 'vue-web-cam'
import createAxios from '/@/utils/axios'
// import { blob } from 'stream/consumers'
// import { createFFmpeg } from 'ffmpeg'
const props = defineProps({
    modelValue: Boolean,
    data: Object,
})
let loading = ref(false)

let visible = ref(false)
const orderinfo: any = ref({})
const express_info: any = ref({})
const order_goods: any = ref([])
const radioValue = ref(0)
const remark: any = ref('')
const consult_money: any = ref('')
// const remark: any = ref('')

// const load = () => {
//     // GetOrderDteail()
// }

const emits = defineEmits(['close', 'update'])
const handleClose = () => {
    emits('close', false) // 可以更新 v-model 绑定的值
}
const changeRadio = (value: any) => {
    // console.log('value', radioValue.value)
    if (radioValue.value === 1) {
        remark.value = ''
        consult_money.value = ''
    } else if (radioValue.value === 2) {
        remark.value = ''
        remark.value = ''
    } else {
        consult_money.value = ''
    }
}
// 录制视频
// const Start = ref(false)
const mediaStream = ref<MediaStream | null>(null)
const mediaRecorder = ref<MediaRecorder | null>(null)
const chunks: Blob[] = []
const recording = ref(false)
const videoUrl = ref('')
const video = ref()
const size = ref()
const videoshow = ref(false)

const startRecording = async () => {
    // Start.value = true
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true })
        mediaStream.value = stream
        video.value.srcObject = stream
        mediaRecorder.value = new MediaRecorder(stream)
        mediaRecorder.value.ondataavailable = (event) => {
            if (event.data.size > 0) {
                chunks.push(event.data)
            }
        }
        mediaRecorder.value.start()
        recording.value = true
    } catch (error) {
        ElMessage({ type: 'warning', message: '获取摄像头权限失败' })
        console.error('Error accessing webcam:', error)
    }
}

const stopRecording = () => {
    if (mediaRecorder.value && mediaStream.value) {
        mediaRecorder.value.stop()
        mediaStream.value.getTracks().forEach((track) => track.stop())
        recording.value = false
        // saveRecording()
        // console.log('123')
    }
}

const downloadVideo = async () => {
    if (chunks.length > 0) {
        console.log('chunks', chunks)
        const blob = new Blob(chunks, { type: 'video/mp4' })

        // console.log('bolb', blob)
        // const url = URL.createObjectURL(blob)
        // console.log('url', url)
        // const a = document.createElement('a')
        // a.href = url
        // a.download = 'recorded-video.mp4'
        // document.body.appendChild(a)
        // a.click()
        // document.body.removeChild(a)
        // URL.revokeObjectURL(url)
        // chunks.length = 0

        uploadVideo(blob)
    } else {
        console.error('No video recorded')
    }
}
// 在需要的地方调用该函数

const uploadVideo = async (blob: Blob) => {
    console.log('blob', blob)
    let formate = new FormData()
    formate.append('file', blob, 'video.mp4')
    console.log(formate.get('file'), 'form')
    createAxios({ url: '/admin/ajax/video', method: 'POST', data: formate })
        .then((res) => {
            console.log(res, 'res')
            loading.value = true
            ElMessage({ type: 'success', message: '上传成功' })
            video.value.src = res.data.url
            videoSrc.value = res.data.url
            videoshow.value = true
            videoUrl.value = res.data.url
        })
        .catch((error) => {
            console.log(error, 'err')
        })
        .finally(() => {
            loading.value = false
        })
}
watch(
    () => props.modelValue,
    (val) => {
        visible.value = val
        GetOrderDteail()
        radioValue.value = 0
        consult_money.value = ''
        remark.value = ''
        videoshow.value = false
    }
)
const handleSave = async () => {
    if (!radioValue.value) {
        ElMessage({ type: 'warning', message: '请选择收获类型' })
        return
    }
    if (radioValue.value == 2 && !remark.value) {
        ElMessage({ type: 'warning', message: '请输入拒绝理由' })
        return
    }
    if (radioValue.value == 3) {
        if (!consult_money.value) {
            ElMessage({ type: 'warning', message: '请输入协商金额' })
            return
        }
        if (!remark.value) {
            ElMessage({ type: 'warning', message: '请输入协商原因' })
            return
        }
    }
    if (!videoUrl.value) {
        ElMessage({ type: 'warning', message: '您未录制开箱视频' })
        return
    }
    let formdata = {
        type: radioValue.value,
        id: props.data,
        remark: remark.value,
        unboxing_video: videoUrl.value,
        consult_money: consult_money.value,
    }
    await createAxios({ url: '/admin/order.Order/check', method: 'POST', data: formdata })
        .then((res) => {
            console.log('res')
        })
        .catch((err) => {
            console.log('err', err)
        })
    await emits('update')
    await handleClose()
}
const videoSrc = ref('')
const GetOrderDteail = () => {
    loading.value = true
    createAxios({ url: '/admin/order.Order/detail', method: 'get', params: { order_id: props.data } }).then((res) => {
        orderinfo.value = res.data
        express_info.value = res.data.order_delivery[0]
        order_goods.value = res.data.order_goods
        videoSrc.value = res.data.unboxing_video
        if (res.data.status == 2) {
            remark.value = res.data.shop_remark
            consult_money.value = res.data.consult_money
            radioValue.value = 3
        }
    })
}
</script>

<style scoped lang="scss">
.contaoner {
    display: flex;
    justify-content: space-between;
    .infinite-list {
        height: 300px;
        padding: 0;
        margin: 0;
        list-style: none;
    }
    .left,
    .right {
        width: 50%;
        .title {
            font-size: 20px;
            color: #000;
            font-weight: 500;
            margin-bottom: 15px;
        }
    }
}
</style>
